#!/bin/bash
# GoSpeed 多架构构建脚本
# 支持构建 linux/amd64, linux/arm64, linux/arm/v7, linux/arm/v6

set -e

echo "🚀 GoSpeed 多架构构建脚本"
echo "支持架构: linux/amd64, linux/arm64, linux/arm/v7, linux/arm/v6"

# 检查是否安装了 buildx 插件
if ! docker buildx version &> /dev/null; then
    echo "❌ Docker Buildx 插件未安装，请先安装 Docker Buildx"
    echo "安装指南: https://docs.docker.com/buildx/"
    exit 1
fi

# 检查是否有可用的构建器
if ! docker buildx ls | grep -q "multiarch"; then
    echo "📦 创建多架构构建器..."
    docker buildx create --name multiarch --driver docker-container --use
else
    echo "✅ 使用现有的 multiarch 构建器"
    docker buildx use multiarch
fi

# 启动构建器
echo "🚀 启动多架构构建器..."
docker buildx inspect --bootstrap

# 设置镜像标签
TAG=${1:-"gospeed:multiarch"}
PLATFORMS="linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6"

echo "📦 构建多架构镜像..."
echo "标签: $TAG"
echo "平台: $PLATFORMS"

# 构建多架构镜像
docker buildx build \
    --platform $PLATFORMS \
    --tag $TAG \
    --file Dockerfile.multiarch \
    --push \
    .

echo "✅ 多架构镜像构建完成！"
echo "📋 镜像信息:"
echo "   标签: $TAG"
echo "   平台: $PLATFORMS"
echo ""
echo "🧪 测试命令:"
echo "   docker run --rm $TAG --version"
echo ""
echo "📤 推送命令（已自动推送）:"
echo "   docker buildx build --platform $PLATFORMS --tag $TAG --push ."
echo ""
echo "🔍 查看镜像详情:"
echo "   docker buildx imagetools inspect $TAG"